<?php

namespace addons\cloud_market\controller\api;

use addons\cloud_market\model\CloudMarketAddon;
use addons\cloud_market\model\CloudMarketSite;
use addons\cloud_market\model\CloudMarketSiteAddon;

/**
 * 应用接口
 */
class Addon extends CloudMarketApiController
{
    protected $notApiLogin = ['checkBuy', 'getRecommendAddon', 'list', 'getAddon'];
    protected $notApiCheck = ['*'];

    /**
     * @var CloudMarketAddon
     */
    protected $model;

    protected function initialize()
    {
        parent::initialize();
        $this->model = new CloudMarketAddon();
    }

    /**
     * 首页
     */
    public function index()
    {
        return $this->success('请求成功');
    }

    /**
     * 【商城】获取列表
     */
    public function list()
    {
        $user = $this->getUser();
        $mix = ['where' => ['status', '>', '0']];
        $mix['field'] = [['id', 'name', 'title', 'price', 'visit', 'icon_image', 'pic_images', 'label_ids', 'type', 'deliver','description']];
        $mix['cache'] = [true];
        if (isset($user) && $user['username'] == 'admin') $mix = [];
//        $mix = [];
        $res = $this->model->getPageList($mix);
        return $this->success('ok', [
            'count' => $res['count'],
            'data'  =>$res['data']->append([
                'pic_image_url',
                'buy_count',
                'token_count',
                'package_count',
                'sku_price',
                'label_names'
            ])
        ]);
    }

    /**
     * 【商城】获取推荐应用 废除
     */
    public function getRecommendAddon()
    {
        $addons = $this->model
            ->where(['status' => 2])
            ->field(['id', 'name', 'title', 'price', 'visit', 'icon_image', 'pic_images', 'label_ids', 'type', 'deliver'])
            ->order('id', 'desc')
            ->cache(true, 600) // 缓存10分钟
            ->select();

        $data = [];
        foreach ($addons as $addon) {
            $addonArray = $addon->toArray();
            // 添加图片URL
            if (isset($addonArray['pic_images'])) {
                $addonArray['pic_image_url'] = cdnurl($addonArray['pic_images']);
            }
            // 添加标签
            if (isset($addonArray['label_ids'])) {
                $addonArray['labels'] = explode(',', $addonArray['label_ids']);
            }
            $data[] = $addonArray;
        }

        return $this->success('', $data);
    }

    /**
     * 【商城】获取单条应用详情
     */
    public function getAddon()
    {
        $id = intval(input('id', 0));
        $name = input('name', '');
        if (!$id && !$name) {
            return $this->error('参数错误');
        }
        $query = $this->model;
        if ($id) {
            $query = $query->where(['id' => $id]);
        } else {
            $query = $query->where(['name' => $name]);
        }
        $addon = $query->find();
        if (!$addon) {
            return $this->error('应用不存在');
        }

        $addonArray = $addon->append(['skus','token_count','new_version','developer','buy_count','docs','version_list'])->toArray();
        // 访问量统计（防止重复统计）
        $ip = getClientIP();
        $key = 'ip_' . $ip . '_visit_addon_' . $id;
        $ip_cache = cache($key);
        if (!$ip_cache) {
            $addon->visit = $addon->visit + 1;
            $addon->save();
            cache($key, 1, 3600); // 缓存1小时
        }
//        if(!count($addonArray['pic_images'])){
//            $addonArray['pic_images'] = [$addonArray['icon_image']];
//        }
        return $this->success('', $addonArray);
    }

    /**
     * 【商城】检查是否购买
     */
    public function checkBuy()
    {
        $site_id = input('site_id', '0');
        $addon_id = input('addon_id', '0');

        if (!$site_id || !$addon_id) {
            return $this->error('参数错误');
        }

        $where = ['site_id' => $site_id, 'addon_id' => $addon_id];
        $res = CloudMarketSiteAddon::where($where)->count();

        // 更新站点最后访问时间
        CloudMarketSite::where('id', $site_id)->update(['update_time' => time()]);

        return $this->success('', $res);
    }

    /**
     * 获取应用选项（用于下拉选择）
     */
    public function getAddonsOptions()
    {
        $search = input('search', '');
        $is_buy = input('is_buy', '0');
        $where = [];

        if ($is_buy) {
            $user = $this->getUser();
            if (!$user) {
                return $this->error('用户未登录');
            }

            $site_ids = CloudMarketSite::where(['user_id' => $user['id']])->column('id');
            $addon_ids = CloudMarketSiteAddon::where('site_id', 'in', $site_ids)->column('addon_id');
            $where[] = ['id', 'in', $addon_ids];
        }

        if ($search) {
            $where[] = ['title', 'like', '%' . $search . '%'];
        }

        $res = $this->model->where($where)->field(['id', 'title'])->select();

        $data = [];
        foreach ($res as $value) {
            $data[] = [
                'value' => $value['id'],
                'label' => $value['title'],
            ];
        }

        return $this->success('', $data);
    }

    /**
     * 获取用户已购买的应用列表
     */
    public function getUserAddons()
    {
        $user = $this->getUser();
        if (!$user) {
            return $this->error('用户未登录');
        }

        $site_ids = CloudMarketSite::where(['user_id' => $user['id']])->column('id');
        if (empty($site_ids)) {
            return $this->success('', []);
        }

        $siteAddons = CloudMarketSiteAddon::hasWhere('addon', [], 'addon_id,count,create_time')
            ->where('site_id', 'in', $site_ids)
            ->with([
                'addon' => function ($query) {
                    $query->field(['id', 'name', 'title', 'icon_image', 'version']);
                }
            ])
            ->select();

        $data = [];
        foreach ($siteAddons as $siteAddon) {
            $addonData = $siteAddon->addon->toArray();
            $addonData['count'] = $siteAddon['count'];
            $addonData['buy_time'] = $siteAddon['create_time'];
            $addonData['icon_image_url'] = cdnurl($addonData['icon_image']);
            $data[] = $addonData;
        }

        return $this->success('', $data);
    }
}
